package occ.service
{
import flash.data.*;
import flash.events.*;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;

import occ.model.*;

import mx.collections.ArrayCollection;
import mx.utils.*;

import com.greatwideweb.util.*;
import occ.utils.*
  
  public class Season  extends EventDispatcher
  {
    public static var startDate:Date=null;
    public static var endDate:Date=null;
    public static var seasonId:Number;
    public static var seasonDescr:String;
    public static var status:String;
    public static var seasonGroups:Array;
  
    public static const SEASON_UNDEFINED:String="SEASON_UNDEFINED";
    public static const SEASON_DEFINED:String="SEASON_DEFINED";
    public static const IS_INIT:String="SeasonIsInitilizeds";
    public static const UNDEFINED:String="SeasonIsNotDefined";
    public static const SAVED:String="OnSeasonSaved";
    public static const SAVE_FAILED:String="OnSeasonSavedAttemptFailed";
    
    private var sqlData:Array;
		private var stmt:SQLStatement;
		private var sql:String;
    private var o:Object;
    private var fmtStartDate:String;
    private var fmtEndDate:String;
    private var _startDate:Date;
    private var _endDate:Date;
    private var _descr:String;
    private const groupBreak:int = 14;
    
     public function Season(target:IEventDispatcher=null)
    {
      super(target);
    }
    
    public function init():void
    {
      //trace("getSiteTypes");
      sql=" select start_date, "+
          "       strftime('%Y',start_date)  +0 as start_yyyy, "+ 
          "        strftime('%m',start_date) - 1 as start_mm, "+
          "        strftime('%d',start_date) + 0 as start_dd, "+
          "        end_date , "+
          "         strftime('%Y',end_date)  +0 as end_yyyy, "+
          "        strftime('%m',end_date) - 1 as end_mm, "+
          "        strftime('%d',end_date) + 0 as end_dd, "+
          " season_id, season_descr as descr  "+
          " from season where active_flag ='Y' ";
      stmt = new SQLStatement();
  		stmt.sqlConnection = DatabaseManager.getConnection();
  		stmt.addEventListener( SQLErrorEvent.ERROR, onSQLError );
  		stmt.addEventListener( SQLEvent.RESULT, onSeasonInit );
  		stmt.text = sql;
  		stmt.execute();
    }
    
    public function createSeason(s:Date, e:Date, d:String):void
    {
      _startDate = s;
      _endDate = e;
      _descr = d;
      
      fmtStartDate = DateUtils.getSQLLiteDate(_startDate);
      fmtEndDate = DateUtils.getSQLLiteDate(_endDate);
      sql=" insert into season "+
      " (start_date, end_date, active_flag, season_descr) "+
      " values "+
      " ('" + fmtStartDate + "', '" + fmtEndDate + "', 'Y', '" + _descr + "') ";
      trace("sql: " + sql);
      stmt = new SQLStatement();
  		stmt.sqlConnection = DatabaseManager.getConnection();
      stmt.addEventListener( SQLErrorEvent.ERROR, onSQLError );
  		stmt.addEventListener( SQLEvent.RESULT, getNextSeasonId );
  		stmt.text = sql;
  		stmt.execute();
    }
    
    public function editSeason(s:Date, e:Date, d:String):void
    {
      _startDate = s;
      _endDate = e;
      _descr = d;
      
      fmtStartDate = DateUtils.getSQLLiteDate(_startDate);
      fmtEndDate = DateUtils.getSQLLiteDate(_endDate);
      sql=
      " update season set "+
      " start_date ='" + fmtStartDate + "', end_date='" + fmtEndDate + "', season_descr ='" + _descr + "' "+
      " where season_id = " + seasonId;
      trace(sql);
      stmt = new SQLStatement();
  		stmt.sqlConnection = DatabaseManager.getConnection();
      stmt.addEventListener( SQLErrorEvent.ERROR, onSQLError );
  		stmt.addEventListener( SQLEvent.RESULT, onSaveSeason );
  		stmt.text = sql;
  		stmt.execute();
    }
    
    private function getNextSeasonId(event:SQLEvent):void
    {
      sql="Select last_insert_rowid() as result"; 
      stmt = new SQLStatement();
  		stmt.sqlConnection = DatabaseManager.getConnection();
      stmt.addEventListener( SQLErrorEvent.ERROR, onSQLError );
  		stmt.addEventListener( SQLEvent.RESULT, onReportInsert );
  		stmt.text = sql;
  		stmt.execute();
    }
    
    private function onSaveSeason(event:SQLEvent):void
    {
      startDate = _startDate;
      endDate = _endDate;
      seasonDescr = _descr;
      dispatchEvent(new Event(SAVED));
    }
    
    private function onReportInsert(event:SQLEvent):void
    {
      var newSeasonId:int=-1;
      var result:SQLResult = stmt.getResult();
      try{
        sqlData = result.data;
        for(var i:int=0;i<sqlData.length;i++){
  			  newSeasonId = (sqlData[i] as Object).result;
  			}
      }catch(e:Error){}
      
       if(newSeasonId != -1){
       
         seasonId = newSeasonId;
         startDate = _startDate;
         endDate = _endDate;
         seasonDescr = _descr;
         status = SEASON_DEFINED;
         dispatchEvent(new Event(SAVED));
         
       }else
         dispatchEvent(new Event(SAVE_FAILED));
    }
    
    private function onSeasonInit(event:SQLEvent):void
    {
      trace("Seasonm onSeasonInit");
      var result:SQLResult = stmt.getResult();
      try{
        sqlData = result.data;
        if(sqlData.length == 0 ){
          trace("The length is 0 throw undefined event");
          status = SEASON_UNDEFINED;
          dispatchEvent(new Event(UNDEFINED));
          
        }else
        {
          trace("The length is greater than 1");
          for(var i:int=0;i<sqlData.length;i++){
            o = (sqlData[i] as Object);
    			  startDate=new Date(o.start_yyyy, o.start_mm, o.start_dd);
            endDate=new Date(o.end_yyyy, o.end_mm, o.end_dd);
            seasonId=o.season_id;
            seasonDescr=o.descr;
    			}
        }
      }catch(e:Error){
        trace(e.message);
        dispatchEvent(new Event(UNDEFINED, true));
      }
         
      if(startDate == null)
      {
        trace("StartDate undefined");
        dispatchEvent(new Event(UNDEFINED, true));
        return void;
      }
         
      var x:int=0;
      // generate the season arrays
      var workerDate:Date = startDate;
      var currentDay:int = startDate.getDate();
      
      trace("Before StartDate");
      if(startDate.getDay() > 0)
      {
        var decrementor:int = startDate.getDay();
        for(var i:int=0;i<startDate.getDay();i++)
        {
          var _beforeDay:int =startDate.getDate() - decrementor;
          workerDate = new Date(startDate.getFullYear(), startDate.getMonth(),_beforeDay );
          decrementor--;
          x++;
        }
      }
          
      trace("Before real processing");
      var innerAr:Array = new Array();
      seasonGroups = new Array();
      while( DateUtils.isDateGreater(endDate,workerDate))
      {
        if(x >= groupBreak)
        {
          seasonGroups.push(innerAr);
          innerAr = new Array();
          x =0;
        }
        workerDate = new Date(startDate.getFullYear(), startDate.getMonth(),currentDay );
        innerAr.push(workerDate);
        currentDay++;
        x++;
        
        
      } 
      seasonGroups.push(innerAr);
      status = SEASON_DEFINED;
      trace("Season about to dispatch seasonGroups size: " + seasonGroups.length)
      dispatchEvent(new Event(IS_INIT, true));
    
        
      
    }
    
    private function onSQLError( event:SQLErrorEvent ):void
		{
      trace("Season onSQLError");
			 var errorString:String = "SQL Error: " + event.error.errorID + "nDetails: " + event.error.details + "nDetail Arguments: " +event.error.detailArguments;
 			throw new Error(errorString);
		}
  }
}